/* $RCSFile: RecoverPwd.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/RecoverPwd/RecoverPwd.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:58  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using Trace2    =   System.Diagnostics.Trace;

using AddonNice;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Core;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Authentication;
using AddonNice.Security;
using AddonNice.Settings;
using AddonNice.CRMWrapper;
using AddonNice.Helpers;
using System.Text;

namespace AddonNice.PageModules.RecoverPwd
{
    public partial class RecoverPwd : PortalCRMModuleControl
    {
        #region Global implementation
        public override Guid GuidID
        {
            get
            {
                return new Guid("{98A5FE92-B9A3-4b0c-BAEF-059D19A17849}");
            }
        }
        #endregion Global implementation

        protected void Page_Load(object sender, EventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RecoverPwd Page_Load BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
        }

        void BtnLogin_Click(object sender, ImageClickEventArgs e)
        {
            string url      =   HttpUrlBuilder.BuildUrl("~/Login.aspx",true,DynPageLoc.Login,StStr.LoginPageID);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RecoverPwd BtnLogin_Click url: '{0}'.",url),ModuleTraceSwitch.Sw.Info);
            ADNPage.Redirect(url,true);
        }

        void BtnHome_Click(object sender, ImageClickEventArgs e)
        {
            string url      =   ADNPage.ReturnUrl;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RecoverPwd BtnHome_Click url: {0}.",url),ModuleTraceSwitch.Sw.Info);
            ADNPage.Redirect(url,true);
        }

        // we must take care to free provider from the Validationg pwd event
        protected override void OnUnload(EventArgs e)
        {
            if ( EvPwd != null )
                Membership.Provider.ValidatingPassword -= EvPwd;
            base.OnUnload(e);
        }

        void Provider_ValidatingPassword(object sender, ValidatePasswordEventArgs e)
        {
            bool Ok =   (e.UserName == PasswordRecovery1.UserName);
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RecoverPwd Provider_ValidatingPassword BEG UserName: {0}, internalUserName: {1}, Ok: {2}",
                    e.UserName,PasswordRecovery1.UserName,Ok),SecurityTraceSwitch.Sw.Info);
            if ( Ok )
                newPwd   =   e.Password;
        }

        /// <summary>
        /// Send mail by CRM
        /// </summary>
        void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RecoverPwd PasswordRecovery1_SendingMail BEG UserName: {0}",PasswordRecovery1.UserName),SecurityTraceSwitch.Sw.Info);
            try
            {
                AddonNiceMembershipUser user = (AddonNiceMembershipUser)Membership.GetUser(PasswordRecovery1.UserName);
                string subj                 =   LocalizeHelper.Localize("LOGIN_RECOVER_SUBJECT", "Your password has been recovered");
                ADNDynEmail cmail            =   new ADNDynEmail(Wrapper, subj);
                cmail.SetOwnerFromUserId();
                if (string.IsNullOrEmpty(newPwd))
                    cmail.description       =   e.Message.Body;
                else
                {
                    StringBuilder sb        =   new StringBuilder();
                    string str              =   LocalizeHelper.Localize("LOGIN_RECOVER_BODY_HELLO", "Hello {0},");
                    if ( !string.IsNullOrEmpty(user.nickname) )
                         sb.AppendFormat(str, user.nickname);
                    else sb.AppendFormat(str, user.UserName);
                    sb.AppendLine();
                    if ( Membership.Provider.EnablePasswordRetrieval )
                        str     =   LocalizeHelper.Localize("LOGIN_RECOVER_BODY_PWDREAD", "Your password has been retrieved, it is '{0}'.");
                    else if ( Membership.Provider.EnablePasswordReset ) 
                        str     =   LocalizeHelper.Localize("LOGIN_RECOVER_BODY_PWDGEN", "Your password has been automatically generated, it is '{0}' , use it to access our site and choose a new one.");
                    sb.AppendFormat(str, newPwd);
                    sb.AppendLine();
                    str     =   LocalizeHelper.Localize("LOGIN_RECOVER_BODY_SIGNATURE", "Your system administrator.");
                    cmail.description       =   Server.HtmlEncode(sb.ToString());
                }
                
                cmail.AddDest(user.CustomerId.GetDynUser(Wrapper,ResetWrapper), user.CrmEMail);
                
                ADNDynSystemUser DynSender   =   user.GetImpersonateUser(Wrapper);
                cmail.AddSender(DynSender, DynSender.internalemailaddress);
                
                cmail.directioncode         =   true;
                cmail.mimetype              =   "text/html";
                cmail.sender                =   user.CrmEMail;
                if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RecoverPwd PasswordRecovery1_SendingMail user.mail: {0}, sender.mail: {1}.",user.CrmEMail,DynSender.internalemailaddress),SecurityTraceSwitch.Sw.Info);
                cmail.adminCreate();
                cmail.Send(true);
                e.Cancel = true;// we don't cancel if crm fails: let a chance for this server to sent a reduced version
                if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		        Trace2.WriteLine("[V]RecoverPwd PasswordRecovery1_SendingMail END.",SecurityTraceSwitch.Sw.Info);
            }
            catch (Exception ex1)
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM PasswordRecovery1_SendingMail ex: {0}", ex1),SecurityTraceSwitch.Sw.Info);
                throw;
            }
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]RecoverPwd PasswordRecovery1_SendingMail END.",ModuleTraceSwitch.Sw.Info);
        }

        public override void Page_PreInit(object sender,EventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]RecoverPwd OnPreInit BEG.",ModuleTraceSwitch.Sw.Info);
            string strcult              =   LocalizeHelper.GetCurrentNeutralCultureName();
            if ( PasswordRecovery1.QuestionTemplateContainer != null )
            {
                Control ctl =   PasswordRecovery1.QuestionTemplateContainer.FindControl("BtnValidateAnswer");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Validate_" + strcult;
                    ((ImageButton)ctl).CommandName  =   PasswordRecovery.SubmitButtonCommandName;
                }
                
                ctl =   PasswordRecovery1.QuestionTemplateContainer.FindControl("CancelBtn");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Cancel_" + strcult;
                    ((ImageButton)ctl).Click += new ImageClickEventHandler(BtnHome_Click);
                }
            }

            if ( PasswordRecovery1.UserNameTemplateContainer != null )
            {
                Control ctl =   PasswordRecovery1.UserNameTemplateContainer.FindControl("BtnValidateUser");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Validate_" + strcult;
                }
                ctl =   PasswordRecovery1.UserNameTemplateContainer.FindControl("CancelBtn");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Cancel_" + strcult;
                    ((ImageButton)ctl).Click += new ImageClickEventHandler(BtnHome_Click);
                }
            }
            if ( PasswordRecovery1.SuccessTemplateContainer != null )
            {
                Control ctl =   PasswordRecovery1.SuccessTemplateContainer.FindControl("BtnLogin");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Login_" + strcult;
                    ((ImageButton)ctl).Click += new ImageClickEventHandler(BtnLogin_Click);
                }
                ctl =   PasswordRecovery1.SuccessTemplateContainer.FindControl("BtnHome");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Finish_" + strcult;
                    ((ImageButton)ctl).Click +=new ImageClickEventHandler(BtnHome_Click);
                }
            }
            
            base.Page_PreInit(sender,e);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]RecoverPwd OnPreInit END.",ModuleTraceSwitch.Sw.Info);
        }

        protected override void OnInit(EventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]RecoverPwd OnInit BEG.",ModuleTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]RecoverPwd OnInit END.",ModuleTraceSwitch.Sw.Info);
        }

        MembershipValidatePasswordEventHandler EvPwd    =   null;
        string newPwd                                   =   string.Empty;
        
        private void InitializeComponent()
        {
            Load                                    +=  new EventHandler(Page_Load);
            PasswordRecovery1.MembershipProvider    =   "AddonNiceMembershipProvider";
            PasswordRecovery1.SendingMail           +=  new MailMessageEventHandler(PasswordRecovery1_SendingMail);
            PasswordRecovery1.GeneralFailureText    =   LocalizeHelper.Localize("LOGIN_RECOVER_GENERALFAILURE","You password cannot be retrieved at this time. Please try again later." );
            PasswordRecovery1.QuestionFailureText   =   LocalizeHelper.Localize("LOGIN_RECOVER_QUESTIONFAILURE","Your answer does not match the stored answer. Please try again." );
            PasswordRecovery1.UserNameFailureText   =   LocalizeHelper.Localize("LOGIN_RECOVER_USERNAMEFAILURE","We couldn't find that user name. Please try again.");
            
            // This is to try getting the new pwd because renewpassword don't give access to it before ceating mail body with default values
            EvPwd    =   new MembershipValidatePasswordEventHandler(Provider_ValidatingPassword);
            Membership.Provider.ValidatingPassword  +=    EvPwd;
            // We need to set something here, else MAilDefinition will go in the smtp config to get default From email and throw an exception if not there....
            PasswordRecovery1.MailDefinition.From   =   Config.EmailFrom;
            PasswordRecovery1.MailDefinition.Subject =  LocalizeHelper.Localize("LOGIN_RECOVER_SUBJECT", "Your password has been recovered");
        }

    }
}
